package com.sjgame.quartz;

import com.sjgame.base.common.JsonResult;
import com.sjgame.base.controller.BaseController;
import com.sjgame.base.entity.Role;
import com.sjgame.quartz.entity.QuartzEntityDto;
import com.sjgame.quartz.service.QuartzService;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import com.sjgame.quartz.entity.QuartzEntity;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * create by zcl
 */
@Controller
@RequestMapping("/task")
public class QuartzController extends BaseController {
    private final static Logger log = LoggerFactory.getLogger(QuartzController.class);

    @Autowired @Qualifier("Scheduler")
    private Scheduler scheduler;
    @Autowired
    private QuartzService quartzService;
    @RequestMapping(value = {"/index"})
    public String index(ModelMap map,String account) {
        Sort t  = new Sort(Sort.Direction.DESC,"createTime");
        Page<QuartzEntity> page = quartzService.findAll(new Specification<QuartzEntity>() {
            @Override
            public Predicate toPredicate(Root<QuartzEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Path<String> namepath = root.get("userName");
                List<Predicate> list = new ArrayList<Predicate>();
                if(account!=null&&!"".equals(account)) {
                    list.add(cb.like(namepath,"%"+account+"%"));
                }

                Predicate[] p = new Predicate[list.size()];
                return cb.and(list.toArray(p));
            }
        },getPageRequest(t));
        map.put("pageInfo", page);
        map.put("account", account);

        return "quartz/index";
    }


    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(ModelMap map) {
        return "quartz/form";
    }


    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public String edit(@PathVariable Integer id, ModelMap map) {
        QuartzEntity quartzEntity = quartzService.find(id);
        map.put("quartzEntity", quartzEntity);
        return "quartz/form";
    }

    @RequestMapping(value = {"/edit"}, method = RequestMethod.POST)
    @ResponseBody
    public JsonResult edit(QuartzEntityDto quartzEntity, ModelMap map) {
        try {

            //如果是修改  展示旧的 任务
            if(!StringUtils.isEmpty(quartzEntity.getId())){
                JobKey key = new JobKey(quartzEntity.getOldQuartzName(),quartzEntity.getOldGrop());
                scheduler.deleteJob(key);
            }
            Class cls = Class.forName(quartzEntity.getClassPath()) ;
            cls.newInstance();
            //构建job信息
            JobDetail job = JobBuilder.newJob(cls).withIdentity(quartzEntity.getQuartzName(),
                    quartzEntity.getQuartzGrop())
                    .withDescription(quartzEntity.getRemark()).build();
            // 触发时间点
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(quartzEntity.getCronExpression());
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger"+quartzEntity.getQuartzName(),   quartzEntity.getQuartzGrop())
                    .startNow().withSchedule(cronScheduleBuilder).build();
            //交由Scheduler安排触发
            scheduler.scheduleJob(job, trigger);

            QuartzEntity quartzEntity1 = new QuartzEntity();
            BeanUtils.copyProperties(quartzEntity,quartzEntity1);
            quartzEntity.setCreateTime(new Date());
            if(StringUtils.isEmpty(quartzEntity.getId())){
                quartzService.save(quartzEntity1);
            }else{
                quartzService.update(quartzEntity1);
            }

        } catch (Exception e) {
            return JsonResult.failure(e.getMessage());
        }
        return JsonResult.success();
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult delete(@PathVariable Integer id, ModelMap map) {
        try {
            QuartzEntity quartzEntity = quartzService.find(id);
            TriggerKey triggerKey = TriggerKey.triggerKey(quartzEntity.getQuartzName(),
                    quartzEntity.getQuartzGrop());
            // 停止触发器
            scheduler.pauseTrigger(triggerKey);
            // 移除触发器
            scheduler.unscheduleJob(triggerKey);
            quartzService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.failure("删除失败");
        }
        return JsonResult.success();
    }

    @RequestMapping(value = "/stop/{id}", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult stop(@PathVariable Integer id, ModelMap map) {
        try {
            QuartzEntity quartzEntity = quartzService.find(id);
            JobKey key = new JobKey(quartzEntity.getQuartzName(),
                    quartzEntity.getQuartzGrop());
            scheduler.pauseJob(key);
            quartzService.update(quartzEntity);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.failure("停止失败");
        }
        return JsonResult.success();
    }

    @RequestMapping(value = "/resume/{id}", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult resume(@PathVariable Integer id, ModelMap map) {
        try {
            QuartzEntity quartzEntity = quartzService.find(id);

            JobKey key = new JobKey(quartzEntity.getQuartzName(),
                    quartzEntity.getQuartzGrop());
            scheduler.resumeJob(key);
            quartzService.update(quartzEntity);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.failure("恢复失败");
        }
        return JsonResult.success();
    }

}
